#!/bin/bash

# Hysteria Rust Installation Script

set -e

echo "Installing Hysteria Rust..."

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo "Please run as root (use sudo)"
    exit 1
fi

# Detect OS
OS="$(uname -s)"
ARCH="$(uname -m)"

echo "Detected OS: $OS"
echo "Detected Architecture: $ARCH"

# Download binary
DOWNLOAD_URL="https://github.com/your-repo/hysteria-rust/releases/latest/download"

case "$OS" in
    Linux)
        BINARY_NAME="hysteria-linux-amd64"
        ;;
    Darwin)
        BINARY_NAME="hysteria-macos-amd64"
        ;;
    *)
        echo "Unsupported OS: $OS"
        exit 1
        ;;
esac

echo "Downloading $BINARY_NAME..."
curl -L "$DOWNLOAD_URL/$BINARY_NAME" -o /tmp/hysteria

# Install binary
echo "Installing to /usr/local/bin..."
chmod +x /tmp/hysteria
mv /tmp/hysteria /usr/local/bin/hysteria

# Create directories
echo "Creating directories..."
mkdir -p /etc/hysteria
mkdir -p /var/lib/hysteria
mkdir -p /var/log/hysteria

# Create user
if ! id -u hysteria > /dev/null 2>&1; then
    echo "Creating hysteria user..."
    useradd -r -s /bin/false hysteria
fi

# Set permissions
chown -R hysteria:hysteria /etc/hysteria
chown -R hysteria:hysteria /var/lib/hysteria
chown -R hysteria:hysteria /var/log/hysteria

# Install systemd service
echo "Installing systemd service..."
cat > /etc/systemd/system/hysteria.service << 'EOF'
[Unit]
Description=Hysteria Proxy Server
After=network.target

[Service]
Type=simple
User=hysteria
ExecStart=/usr/local/bin/hysteria server -c /etc/hysteria/server.yaml
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
EOF

cat > /etc/systemd/system/hysteria-admin.service << 'EOF'
[Unit]
Description=Hysteria Admin Panel
After=network.target

[Service]
Type=simple
User=hysteria
ExecStart=/usr/local/bin/hysteria admin -c /etc/hysteria/admin.yaml
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
EOF

# Reload systemd
systemctl daemon-reload

echo ""
echo "Installation completed successfully!"
echo ""
echo "Next steps:"
echo "1. Create configuration files in /etc/hysteria/"
echo "2. Start the service: systemctl start hysteria"
echo "3. Enable auto-start: systemctl enable hysteria"
echo ""
echo "For more information, visit: https://github.com/your-repo/hysteria-rust"
